# -*- coding: utf-8 -*-
"""
日志管理模块
"""
import logging
import os
from datetime import datetime
from config import APP_NAME
from .path_manager import get_logs_dir

class Logger:
    """日志管理器"""
    
    def __init__(self, log_dir=None):
        self.log_dir = log_dir or get_logs_dir()
        self._setup_logger()
    
    def _setup_logger(self):
        """设置日志器"""
        # 创建日志器
        self.logger = logging.getLogger(APP_NAME)
        self.logger.setLevel(logging.DEBUG)
        
        # 避免重复添加处理器
        if self.logger.handlers:
            return
        
        # 创建文件处理器
        log_file = os.path.join(self.log_dir, f"{APP_NAME}_{datetime.now().strftime('%Y%m%d')}.log")
        file_handler = logging.FileHandler(log_file, encoding='utf-8')
        file_handler.setLevel(logging.DEBUG)
        
        # 创建控制台处理器
        console_handler = logging.StreamHandler()
        console_handler.setLevel(logging.INFO)
        
        # 创建格式器
        formatter = logging.Formatter(
            '%(asctime)s - %(name)s - %(levelname)s - %(message)s',
            datefmt='%Y-%m-%d %H:%M:%S'
        )
        
        file_handler.setFormatter(formatter)
        console_handler.setFormatter(formatter)
        
        # 添加处理器到日志器
        self.logger.addHandler(file_handler)
        self.logger.addHandler(console_handler)
    
    def debug(self, message: str):
        """调试日志"""
        self.logger.debug(message)
    
    def info(self, message: str):
        """信息日志"""
        self.logger.info(message)
    
    def warning(self, message: str):
        """警告日志"""
        self.logger.warning(message)
    
    def error(self, message: str):
        """错误日志"""
        self.logger.error(message)
    
    def critical(self, message: str):
        """严重错误日志"""
        self.logger.critical(message)
    
    def log_exception(self, message: str = ""):
        """记录异常"""
        self.logger.exception(message)
    
    def log_database_connection(self, host: str, port: int, database: str, username: str, success: bool, error_msg: str = ""):
        """记录数据库连接日志"""
        if success:
            self.info(f"数据库连接成功: {username}@{host}:{port}/{database}")
        else:
            self.error(f"数据库连接失败: {username}@{host}:{port}/{database} - {error_msg}")
    
    def log_export_operation(self, database_name: str, table_count: int, export_format: str, 
                           file_path: str, success: bool, error_msg: str = ""):
        """记录导出操作日志"""
        if success:
            self.info(f"导出成功: {database_name} - {table_count}张表 - {export_format} - {file_path}")
        else:
            self.error(f"导出失败: {database_name} - {table_count}张表 - {export_format} - {file_path} - {error_msg}")
    
    def log_user_action(self, action: str, details: str = ""):
        """记录用户操作日志"""
        self.info(f"用户操作: {action} - {details}")
    
    def log_system_event(self, event: str, details: str = ""):
        """记录系统事件日志"""
        self.info(f"系统事件: {event} - {details}")

# 创建全局日志器实例
logger = Logger()
